<template>
  <div class="search">
    <!-- 添加按钮 -->
    <!-- 搜索 -->
    <Row>
      <Col>
        <Card>
          <Row class="operation">
            <Col :span="4">
              <Button @click="getList" icon="md-refresh" style="margin-right:10px">刷新</Button>
            </Col>
            <Col :span="20">
              <Form ref="searchForm" inline :model="searchForm" :label-width="85">
                <FormItem label="商品分类">
                  <Poptip trigger="click" placement="right-start" title="分类" width="100%">
                    <Input v-model="searchForm.goodCategoryName" style="width:100%" readonly placeholder="请选择商品分类" />
                    <div slot="content" style="position:relative;min-height:5vh">
                      <Tree :data="classifyData" :load-data="loadData" @on-select-change="selectOneTreeEdit" ref="treeOne"></Tree>
                      <Spin size="large" fix v-if="loadingEdit"></Spin>
                    </div>
                  </Poptip>
                </FormItem>
                <FormItem label="商家名称">
                  <Input v-model="searchForm.shopName" clearable placeholder="请输入商家名称" class="itemInput" />
                </FormItem>
                <FormItem label="商品名称">
                  <Input v-model="searchForm.goodName" clearable placeholder="请输入商品名称" class="itemInput" />
                </FormItem>
                <Form-item style="margin-left:-40px">
                  <Button type="default" @click="clearIpt" style="margin-right:10px">清空</Button>
                  <Button type="primary" @click="getList" style="margin-right:10px">搜索</Button>
                </Form-item>
              </Form>
            </Col>
          </Row>
          <Row>
            <Table :loading="loading" border :columns="commodityColumns" :data="commodityData" ref="table" sortable="custom" @on-sort-change="changeSort"></Table>
          </Row>
          <Row type="flex" justify="end" class="page">
            <Page :current="searchForm.pageNumber" :total="pageTotal" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
          </Row>
        </Card>
      </Col>
    </Row>
    <!-- 查看大图 -->
    <Modal title="查看大图" v-model="visible" class="imgModal">
      <img :src="imgSrc" style="width: 100%" />
    </Modal>
    <!-- 添加商品 -->
    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable="false" :width="800">
      <Form ref="addForm" :model="addForm" :label-width="100" :rules="formRules">
        <FormItem label="商品名称" prop="goodName">
          <Input v-model="addForm.goodName" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="商品分类" prop="goodCategoryId">
          <Poptip trigger="click" placement="right-start" title="分类" width="100%">
            <Input v-model="addForm.goodCategoryName" style="width:100%" readonly placeholder="请选择商品分类" />
            <div slot="content" style="position:relative;min-height:5vh">
              <Tree :data="classifyData" :load-data="loadData" @on-select-change="selectTwoTreeEdit" ref="treeTwo"></Tree>
              <Spin size="large" fix v-if="loadingEdit"></Spin>
            </div>
          </Poptip> 
        </FormItem>
        <FormItem label="商品原价" prop="goodOldPrice">
          <Input v-model="addForm.goodOldPrice" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="商品现价" prop="goodNewPrice">
          <Input v-model="addForm.goodNewPrice" placeholder="请输入商品名称" />
        </FormItem>
        <FormItem label="积分" prop="integral">
          <InputNumber v-model="addForm.integral" placeholder="请输入积分" style="width: 100%"></InputNumber>
        </FormItem>
        <FormItem label="商品图片" prop="goodPics">
          <upload-pic-input v-model="addForm.goodPics"></upload-pic-input>
        </FormItem>
        <FormItem label="商品详情">
          <editor id="editor" v-model="addForm.goodDetails" ref="editor"></editor>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="cancel">取消</Button>
        <Button type="primary" @click="handleSubmit('form')">提交</Button>
      </div>
    </Modal>

    <!-- 规格列表 -->
    <Modal title="商品规格" v-model="lookPreVisible" :mask-closable='false' :width="600">
      <Button type="primary" @click="addSpecification">添加</Button>
      <!-- <Button type="default" @click="delAllSpecification">批量删除</Button> -->
      
      <Row style="margin-top:30px;">
        <Table :loading="loading" border :columns="specificationColumns" :data="specificationData"  ref="table" sortable="custom" @on-sort-change="changeSort" @on-selection-change="changeSelect"></Table>
      </Row>
      <!-- <Row type="flex" justify="end" class="page">
        <Page :current="searchForm.pageNumber" :total="1" :page-size="searchForm.pageSize" @on-change="changePage" @on-page-size-change="changePageSize" :page-size-opts="[10,20,50]" size="small" show-total show-elevator show-sizer></Page>
      </Row> -->
    </Modal>

    <!-- 商品规格添加 -->
    <Modal title="商品规格" v-model="preVisible" :mask-closable='false' :width="600">
      <Form ref="preForm" :model="preForm" :label-width="100" :rules="preFormValidate" >
        <FormItem label="规格图片" prop="pic" >
         <upload-pic-input v-model="preForm.pic" style="width:100%"></upload-pic-input>
        </FormItem>
        <FormItem label="规格" prop="attrSymbolPath" v-if="modalStatus === 0">
          <i-select style="width:30%" v-for=" (row, index) in specificationlist" :key="row.id" @on-change="selectSpecification($event, index)">
            <i-option v-for="item in row.children" :key="item.id" :value="item.id" @click="getAttrIds(item)">{{item.title}}</i-option>
          </i-select>
        </FormItem>
        <FormItem label="价格" prop="goodPrice" >
          <Input v-model="preForm.goodPrice" style="width:100%"></Input>
        </FormItem>
        <FormItem label="库存" prop="inventory" >
          <InputNumber v-model="preForm.inventory" style="width:100%"></InputNumber>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="preVisible=false">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="preHandleSubmit" >提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  getCategoryList,
  getCommodityList,
  editCommodity,
  removeCommodity,
  addCommodity,
  getColorList,
  getSizeList
} from "@/api/commodity";
import uploadPicInput from "@/views/my-components/xboot/upload-pic-input";
import editor from "@/views/my-components/xboot/editor";
export default {
  components: {
    uploadPicInput,
    editor
  },
  data() {
    return {
      loading: true,
      visible: false,
      lookPreVisible: false,
      preVisible: false,
      imgSrc: "",
      pageTotal: 0, //总条数
      drop: false, //搜索栏
      modalVisible: false, //模态框的显示隐藏
      modalType: "add", //add: 添加商品     edit编辑商品
      modalTitle: "添加商品",
      commodityData: [],
      category: [],
      color: [],
      size: [],
      loadingEdit: false,
      //商品显示
      commodityColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "商品名称",
          minWidth: 120,
          sortable: false,
          key: "goodName"
        },
        {
          title: "商家名称",
          minWidth: 120,
          sortable: false,
          key: "shopName"
        },  
        {
          title: "商品图片",
          minWidth: 120,
          sortable: false,
          key: "goodPics",
          render: (h, params) => {
            return h("img", {
              attrs: {
                src: params.row.goodPics
              },
              style: {
                width: "30px",
                height: "30px"
              }
            });
          }
        },      
        {
          title: "商品原价",
          minWidth: 120,
          sortable: false,
          key: "goodOldPrice"
        },
        {
          title: "商品现价",
          minWidth: 120,
          sortable: false,
          key: "goodNewPrice"
        },
        {
          title: "分类名称",
          minWidth: 120,
          sortable: false,
          key: "goodCategoryName"
        },
        {
          title: "积分",
          minWidth: 120,
          sortable: false,
          key: "integral"
        },        
        {
          title: "操作",
          width: 260,
          align: "center",
          fixed: "right",
          minWidth: 200,
          render: (h, params) => {
            return h("div", [
              // h(
              //   "Button",
              //   {
              //     props: {
              //       type: "info",
              //       size: "small"
              //     },
              //     style: {
              //       marginRight: "5px"
              //     },
              //     on: {
              //       click: () => {
              //         this.edit(params.row);
              //       }
              //     }
              //   },
              //   "编辑"
              // ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px",
                    display:(params.row.delFlag==1)?"none":"inline-block"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row,1);
                    }
                  }
                },
                "下架"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "default",
                    size: "small"
                  },
                  style: {
                    marginRight: "5px",
                    display:(params.row.delFlag==0)?"none":"inline-block"
                  },
                  on: {
                    click: () => {
                      this.remove(params.row,2);
                    }
                  }
                },
                "上架"
              ),
              
              // h(
              //   "Button",
              //   {
              //     props: {
              //       type: "primary",
              //       size: "small"
              //     },
              //     style: {
              //       marginRight: "5px"
              //     },
              //     on: {
              //       click: () => {
              //         this.showSpecification(params.row);
              //       }
              //     }
              //   },
              //   "添加规格"
              // ),
            ]);
          }
        }
      ],
      searchForm: {
        shopName: "", // 店铺名称
        goodName: "", // 商品名称
        goodCategoryId: "",
        goodCategoryName: "",
        pageNumber: 1,
        pageSize: 10
      },
      addForm: {
        goodCategoryId: "",
        goodName: "",
        goodPics: "",
        goodDetails: "",
        goodOldPrice: "",
        goodNewPrice: "",
        integral: "",
        typeEnum: "GOOD"
      },
      formRules: {
        goodName: [ { required: true, message: "请输入商品名称", trigger: "blur" },
          { type: 'string', max: 30, message: '商品名称不能多于30字', trigger: 'blur' }],
        goodCategoryId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
        goodPics: [{ required: true, message: "请选择商品轮播", trigger: "blur" }],
        goodNewPrice: [{ required: true, message: "请输入商品原价", trigger: "blur",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ },
                    { required: true, message: "商品原价格式不正确",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/}],
        goodOldPrice: [{ required: true, message: "请输入商品现价", trigger: "blur",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ },
                    { required: true, message: "商品现价格式不正确",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/}],
        integral: [ { required: true, message: "商品积分只能为正整数", trigger: "blur", pattern: /(^[1-9]\d*$)/ }],
      },
      preForm: {
        id: "",
        goodsId: "",
        attrSymbolPath: "",
        goodPrice: "",
        integral:0,
        pic: ""
      },
      submitLoading: false,
      specificationlist: [],
      preFormValidate: {
        attrSymbolPath: [{ required: true, message: "请选择规格", trigger: "change" }],
        goodPrice: [{ required: true, message: "请输入规格价格", trigger: "blur", pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/ },
                    { required: true, message: "规格价格格式不正确",pattern:/^(([1-9]\d{0,9})|0)(\.\d{0,2})?$/}],
        inventory: [{ required: true, message: "请输入库存", trigger: "blur", type:"number" },
                    { required: true, message: "规格库存只能为正整数", trigger: "blur", type: "number" }],
        pic: [{ required: true, message: "请选择图片", trigger: "blur" }],
      },
      specificationData: [],
      specificationColumns: [
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "规格名称",
          key: "attrSymbolPathName",
        },
        {
          title: "规格价格",
          key: "goodPrice",
        },
        {
          title: "规格图片",
          key: "pic",
          sortable: false,
          render: (h, params) =>{
            return h('img',{
              attrs:{
                src:params.row.pic,
                onerror:'this.src="https://goss.veer.com/creative/vcg/veer/800water/veer-133632476.jpg"'
              },
              style:{
                width:'42px',
                verticalAlign:'middle',
                cursor:'pointer'
              }
            })
          }
        },
        {
          title: "库存",
          key: "inventory"
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                    icon: "ios-create-outline"
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.editSpecification(params.row);
                    }
                  }
                },
                "编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small",
                  },
                  on: {
                    click: () => {
                      this.removeSpecification(params.row);
                    }
                  }
                },
                "删除"
              ),
            ]);
          }
        }
      ],
      attrIdArr: [],
      goodId: "",
      modalStatus: 0,
      classifyData: [],
    };
  },
  methods: {
    showSpecification (v) {
      this.lookPreVisible = true;
      this.goodId = v.id
      var data = {
        goodsId: this.goodId
      }
      this.postRequest("/sizeAndRolor/getWebInventory", data).then(res=> {
        if (res.success) {
          this.specificationData = res.result.data;
        }
      })
    },

    changeSelect (v) {
      console.log(v)
    },

    changeSort () {

    },

    addSpecification () {
      this.modalStatus = 0;
      var data = {
        classId: ""
      }
      this.postRequest("/itemAttrKey/getItemAttrKeyList", data).then(res=> {
        if (res.success) {
          this.preVisible = true;
          this.specificationlist = res.result
        } else {
          this.specificationlist = [];
          this.$Message.warning("该商品所属分类下没有规格属性，请先去添加规格属性！")
        }
      })
    },

    selectSpecification (e, k) {
      for(var i=0; i<k+1; i++) {
        if (i == k) {
          this.attrIdArr[k] = e
          console.log('id==='+this.attrIdArr[k])
        }
      }
      console.log(this.attrIdArr)
      this.preForm.attrSymbolPath = this.attrIdArr.join(',');
      console.log(this.preForm.attrSymbolPath)
    },

    preHandleSubmit () {
      this.$refs.preForm.validate(valid=> {
        if (valid) {
          console.log(valid)
          if (this.modalStatus === 0) {
            delete this.preForm.id;
            this.preForm.goodsId = this.goodId;
            console.log(this.preForm)
            this.postRequest("/sizeAndRolor/insertOrderUpdateSizeAndRolor", this.preForm).then(res=> {
              if (res.success) {
                this.$Message.success("操作成功");
                this.preVisible = false;
                this.$refs.preForm.resetFields();
                this.attrIdArr = [];
                // this.
                var param = {
                  goodsId: this.goodId
                }
                this.postRequest("/sizeAndRolor/getWebInventory", param).then(res=> {
                  if (res.success) {
                    this.specificationData = res.result.data;
                  }
                })
              }
            })
          } else {
            this.preForm.goodsId = this.goodId;
            console.log(this.preForm)
            this.postRequest("/sizeAndRolor/insertOrderUpdateSizeAndRolor", this.preForm).then(res=> {
              if (res.success) {
                this.$Message.success("操作成功");
                this.preVisible = false;
                this.$refs.preForm.resetFields();
                this.attrIdArr = [];
                var param = {
                  goodsId: this.goodId
                }
                this.postRequest("/sizeAndRolor/getWebInventory", param).then(res=> {
                  if (res.success) {
                    this.specificationData = res.result.data;
                  }
                })
              }
            })
          }
        }
      })
    },
    // 编辑商品规格库存
    editSpecification (v) {
      console.log(v);
      this.modalStatus = 1;
      this.preForm.id = v.id;
      // this.preForm.inventory = v.inventory;
      this.preForm.integral = v.integral;
      this.preForm.goodPrice = v.goodPrice;
      this.preForm.attrSymbolPath = v.attrSymbolPath;
      this.preForm.pic = v.pic;
      this.preVisible = true;
    },

    removeSpecification (v) {
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的规格数据?",
        loading: true,
        onOk: () => {
          var param = {
            ids: v.id
          }
          // 批量删除
          this.postRequest("/sizeAndRolor/removeSizeAndRolor",param).then(res => {
            this.$Modal.remove();
            if (res.success) {
              this.$Message.success("操作成功");
              this.$Modal.remove();
              var data = {
                goodsId: this.goodId
              }
              this.postRequest("/sizeAndRolor/getWebInventory", data).then(res=> {
                if (res.success) {
                  this.specificationData = res.result.data;
                }
              })
            }
          });
        }
      });
    },

    // 获取分类列表
    getCategory() {
      getCategoryList().then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            e.title=e.title;
              if (e.isParent) {
                e.loading = false;
                e.children = [];
              }
            });
          this.classifyData = res.result;
        }
      });
    },

    loadData(item, callback) { 
        // 异步加载树子节点数据
      var param ={
        pid:item.id
      }
      this.postRequest("/goodCategory/getGoodCategoryList",param).then(res => {
        if (res.success) {
          res.result.forEach(function(e) {
            e.title=e.title
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.result);
        }
      });
    },

    selectTwoTreeEdit(v){
      console.log(v);
      if (v[0].parentId === "0") {
        this.$Message.warning("添加或修改商品只能选择子节点")
      } else {
        var data = {
          pid:v[0].id
        }
        this.addForm.goodCategoryId = v[0].id;
        this.addForm.goodCategoryName = v[0].title;
        this.$forceUpdate();
      }
    },

    selectOneTreeEdit(v){
      var data = {
        pid:v[0].id
      }
      this.searchForm.goodCategoryId = v[0].id;
      this.searchForm.goodCategoryName = v[0].title;
      this.$forceUpdate();
    },
    
    clearIpt () {
      this.searchForm.goodCategoryId = "";
      this.searchForm.goodCategoryName = "";
      let data = this.$refs.treeOne.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.searchForm.shopName = "";
      this.searchForm.goodName = "";
    },

    // 获取商品列表
    getList() {
        // 分类id是个数组，这里转为字符串
      let data = {}
      let searchForm = this.searchForm
      for(let key in searchForm) {
          if (Array.isArray(searchForm[key])) {
          // data[key].slice(key.length - 1) 数组的最后一个元素
          let length = searchForm[key].length;
          data[key] = searchForm[key][length - 1];
         } else {
          data[key] = searchForm[key];
         }
      }
      this.loading = true;
      this.postRequest("/good/PCgoodsList", data).then(res=> {
        this.loading = false
        if (res.success) {
          this.commodityData = res.result.data;
          this.pageTotal = res.result.size
        } else {
          this.commodityData = [];
          this.pageTotal = 0
        }
      })
    },

    // 编辑商品
    edit(row) {
      console.log(row);
      this.modalVisible = true;
      this.modalType = "edit";
      this.modalTitle = "编辑商品";
      this.addForm.id = row.id;
      this.addForm.goodCategoryId = row.goodCategoryId;
      this.addForm.goodCategoryName = row.goodCategoryName;
      this.$refs.editor.setData(row.goodDetails);
      // 编辑商品，给表单赋初值
      for (let key in row) {
        // 只给商品现有属性赋值
        if (this.addForm.hasOwnProperty(key)) {
          // 商品有的属性是数组，这里做下判断
          if (this.addForm[key] instanceof Array) {
            // 如果是数组需要push赋值
            this.addForm[key].push(row[key]);
          } else {
            this.addForm[key] = row[key];
          }
        }
      }
    },
    // 添加商品
    showAddModal() {
      // 添加商品不需要商品的id
      delete this.addForm.id;
      let data = this.$refs.treeTwo.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.addForm.goodCategoryId = "";
      this.addForm.goodCategoryName = "";
      this.addForm.goodName = "";
      this.addForm.goodNewPrice = "";
      this.addForm.goodOldPrice = "";
      this.addForm.goodPics = "";
      this.addForm.integral = "";
      var data1 = "";
      this.$refs.editor.setData(data1)
      this.modalVisible = true;
      this.modalType = "add";
      this.modalTitle = "添加商品";
    },
    // 删除商品
    remove(v,k) {
      
          removeCommodity({
            id: v.id
          }).then(res => {
            if(res.success) {
              this.$Message.success('操作成功')
              this.getList();
              this.$Modal.remove()
            }else{
              this.$Message.error('操作失败');
              this.$Modal.remove()
            }
          })
        
    },
    // 切换页
    changePage(num) {
        this.searchForm.pageNumber = num
        this.getList()
    },
    // 切换每页显示条数
    changePageSize (num) {
        this.searchForm.pageSize = num;
        this.getList()
    },
    // 放大图片
    handleView(src) {
      this.visible = true;
      this.imgSrc = src;
    },
    // modal取消按钮
    cancel() {
      this.modalVisible = false;
    },
    // 提交表单，添加、编辑都调用这个
    handleSubmit() {
      // 判断是添加还是编辑
      let modalType = this.modalType;
      this.$refs.addForm.validate(valid => {
        if (valid) {
          // 获取要添加的数据
          let data = {};
          let formdata = this.addForm;
          
          // 添加的数据属性不需要数组，这里分类、颜色直接取数组最后一个值
          for (let key in formdata) {
            if (Array.isArray(formdata[key])) {
              // data[key].slice(key.length - 1) 数组的最后一个元素
              let length = formdata[key].length;
              data[key] = formdata[key][length - 1];
            } else {
              data[key] = formdata[key];
            }
          }
          data.typeEnum = "GOOD";
          if (modalType === "add") {
            //  添加
            addCommodity(data).then(res => {
              this.modalVisible = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getList();
              } else {
                this.$Message.error(res.message);
              }
            });
          } else {
            //  编辑
            editCommodity(data).then(res => {
              this.modalVisible = false;
              if (res.success) {
                this.$Message.success("操作成功");
                this.getList();
              } else {
                this.$Message.error(res.message);
              }
            });
          }
        }
      })
    }
  },
  created() {
    this.getCategory();
    this.getList();
  }
};
</script>

<style>
.commodity-content {
  padding: 16px;
  background-color: #ffffff;
}
.itemInput {
  width: 160px;
}
.selected {
  width: 50%;
}
.imgModal {
  text-align: center;
}
.img {
  width: 50px;
  height: 50px;
}
.page{
        margin: 16px;
        overflow: hidden;
        text-align: right;
    }
</style>